﻿using System;
using System.IO;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using Google.API.Translate;

namespace WordBibliographyAddin
{
    internal static class Utils
    {
        private static readonly TranslateClient googleTranslatorClient;

        static Utils()
        {
            googleTranslatorClient = new TranslateClient("http://www.google.com");
        }

        internal static void ShowKryptonDialog(string mainInstruction, string content, MessageBoxIcon icon, params object[] args)
        {
            using (KryptonTaskDialog dlg = new KryptonTaskDialog())
            {
                dlg.MainInstruction = Utils.TranslateText(mainInstruction);
                dlg.Content = string.Format(Utils.TranslateText(content), args);
                dlg.AllowDialogClose = true;
                dlg.DefaultButton = TaskDialogButtons.OK;
                dlg.Icon = icon;
                dlg.ShowDialog();
            }
        }

        internal static bool HasAdminPrivileges()
        {
            bool hasAccess = false;

            string directory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
            if (directory == null || directory.Length == 0)
                directory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

            string path = Path.Combine(directory, @"dummy");
            try
            {
                using (File.OpenWrite(path))
                    hasAccess = true;
            }
            catch (UnauthorizedAccessException)
            {
                hasAccess = false;
            }
            return hasAccess;
        }

        internal static string GetWordBibliographyStylesFolder()
        {
            string directory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
            if (directory == null || directory.Length == 0)
                directory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

            string path = Path.Combine(directory, @"Microsoft Office\Office12\Bibliography\Style");
            return path;
        }

        internal static string TranslateText(string text)
        {
            Language toLang = Language.English;
            string currentName = InputLanguage.CurrentInputLanguage.Culture.Name.Substring(0, 2);
            foreach (Language item in Language.TranslatableCollection)
            {
                if (item.Value.Equals(currentName, StringComparison.CurrentCultureIgnoreCase))
                {
                    toLang = item;
                    break;
                }
            }

            if (!toLang.Equals(Language.English))
            {

                string translated = googleTranslatorClient.Translate(text.ToLower(), Language.English, toLang);
                return translated;
            }
            return text;
        }

    }
}
